package middleware

/*
 * @Author: chengjiang
 * @Date: 2025-07-26 00:43:09
 * @Description:
 */

import (
	"context"
	"log"
	"time"

	"github.com/go-kratos/kratos/v2/middleware"
	"github.com/go-kratos/kratos/v2/transport/http"
)

func NewLoggingMiddleware() middleware.Middleware {
	return func(handler middleware.Handler) middleware.Handler {
		return func(ctx context.Context, req interface{}) (interface{}, error) {
			// 记录请求信息
			if tr, ok := http.RequestFromServerContext(ctx); ok {
				start := time.Now()
				log.Printf(
					"[REQUEST] 方法: %s, 路径: %s, 客户端IP: %s",
					tr.Method,
					tr.URL.Path,
					tr.RemoteAddr,
				)

				// 执行后续处理
				resp, err := handler(ctx, req)

				// 记录响应信息
				log.Printf(
					"[RESPONSE] 耗时: %v, 错误: %v",
					time.Since(start),
					err,
				)
				return resp, err
			}
			return handler(ctx, req)
		}
	}
}
